namespace DeleteOnTimeTool
{
	public partial class mainForm : Form
	{
		private Models.AppConfig _config = new();
		private BindingSource _bindingSource = new();

		public mainForm()
		{
			InitializeComponent();
			LoadConfig();
			InitGrid();
			InitUiFromConfig();
		}

		private void LoadConfig()
		{
			_config = Services.ConfigService.Load();
		}

		private void SaveConfig()
		{
			Services.ConfigService.Save(_config);
		}

		private void InitGrid()
		{
			// 确保表头可见
			gridTasks.ColumnHeadersVisible = true;
			gridTasks.EnableHeadersVisualStyles = true;
			
			// 启用双缓冲以减少闪烁
			typeof(DataGridView).InvokeMember("DoubleBuffered", 
				System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic,
				null, gridTasks, new object[] { true });
			
			// 设置基准时间列的数据源
			var basisColumn = gridTasks.Columns["Basis"] as DataGridViewComboBoxColumn;
			if (basisColumn != null)
			{
				basisColumn.DataSource = Enum.GetValues(typeof(Models.TimeBasis));
			}

			_bindingSource.DataSource = _config.Tasks;
			gridTasks.DataSource = _bindingSource;

			// 确保存在序号列（未绑定列）
			if (gridTasks.Columns["RowNumber"] == null)
			{
				var rowNumCol = new DataGridViewTextBoxColumn
				{
					Name = "RowNumber",
					HeaderText = "序号",
					ReadOnly = true,
					Width = 60,
					Frozen = true
				};
				gridTasks.Columns.Insert(0, rowNumCol);
			}

			// 将 Basis 列替换为下拉框列（绑定到枚举），若尚未为下拉框
			if (gridTasks.Columns["Basis"] != null && gridTasks.Columns["Basis"] is not DataGridViewComboBoxColumn)
			{
				var basisIndex2 = gridTasks.Columns["Basis"].Index;
				gridTasks.Columns.RemoveAt(basisIndex2);
				var basisCombo = new DataGridViewComboBoxColumn
				{
					Name = "Basis",
					HeaderText = "基准时间",
					DataPropertyName = "Basis",
					DataSource = Enum.GetValues(typeof(Models.TimeBasis)),
					DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
				};
				gridTasks.Columns.Insert(basisIndex2, basisCombo);
			}
			
			// 添加行号更新事件
			gridTasks.DataBindingComplete += GridTasks_DataBindingComplete;
		}

		private void InitUiFromConfig()
		{
			_bindingSource.ResetBindings(false);
			// 初始化每日执行时间输入框
			if (TimeSpan.TryParse(_config.DailyRunHour, out var dailyTime))
			{
				var today = DateTime.Today;
				txtDailyRunHour.Value = today.Add(dailyTime);
			}
			else
			{
				// 无效配置时，回退到 02:30:00
				var fallback = new TimeSpan(2, 30, 0);
				txtDailyRunHour.Value = DateTime.Today.Add(fallback);
			}
			UpdateTaskButtonStates();
		}

		private bool TryUpdateDailyRunHourFromUi()
		{
			// 直接从时间控件读取并格式化
			_config.DailyRunHour = txtDailyRunHour.Value.ToString("HH:mm:ss");
			return true;
		}

		private void UpdateTaskButtonStates()
		{
			var isRegistered = Services.SchedulerService.IsTaskRegistered();
			btnRegister.Enabled = !isRegistered;
			btnUnregister.Enabled = isRegistered;
		}

		private void btnSave_Click(object? sender, EventArgs e)
		{
			gridTasks.EndEdit();
			_bindingSource.EndEdit();
			if (!TryUpdateDailyRunHourFromUi()) return;
			SaveConfig();
			MessageBox.Show("已保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		private void btnRunNow_Click(object? sender, EventArgs e)
		{
			gridTasks.EndEdit();
			_bindingSource.EndEdit();
			if (!TryUpdateDailyRunHourFromUi()) return;
			SaveConfig();
			Services.LogService.WriteInfo(_config, "手动执行开始");
			var count = Services.DeleteService.Execute(_config);
			MessageBox.Show($"执行完成，删除 {count} 个文件", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		private void btnRegister_Click(object? sender, EventArgs e)
		{
			gridTasks.EndEdit();
			_bindingSource.EndEdit();
			if (!TryUpdateDailyRunHourFromUi()) return;
			SaveConfig();
			Services.SchedulerService.RegisterDailyTask(_config.DailyRunHour);
			MessageBox.Show("已注册 Windows 计划任务（每日自动执行）", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
			UpdateTaskButtonStates();
		}

		private void btnUnregister_Click(object? sender, EventArgs e)
		{
			var confirm = MessageBox.Show("确认取消每日计划任务吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
			if (confirm != DialogResult.Yes) return;

			Services.SchedulerService.UnregisterDailyTask();
			MessageBox.Show("已取消 Windows 计划任务", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
			UpdateTaskButtonStates();
		}

		private Models.DeleteTask? GetSelectedTask()
		{
			gridTasks.EndEdit();
			_bindingSource.EndEdit();

			DataGridViewRow? candidate = null;
			if (gridTasks.CurrentCell != null)
			{
				candidate = gridTasks.Rows[gridTasks.CurrentCell.RowIndex];
			}
			if (candidate == null && gridTasks.SelectedRows.Count > 0)
			{
				candidate = gridTasks.SelectedRows[0];
			}
			if (candidate == null && gridTasks.CurrentRow != null)
			{
				candidate = gridTasks.CurrentRow;
			}

			var task = candidate?.DataBoundItem as Models.DeleteTask;
			if (task != null) return task;

			// 回退到绑定源当前项（处理键盘导航但未触发行变更的情形）
			return _bindingSource.Current as Models.DeleteTask;
		}

		private void gridTasks_SelectionChanged(object? sender, EventArgs e)
		{
			if (gridTasks.CurrentRow == null) return;
			var task = gridTasks.CurrentRow.DataBoundItem as Models.DeleteTask;
			if (task == null) return;
			var index = _config.Tasks.IndexOf(task);
			if (index >= 0 && index < _bindingSource.Count)
				_bindingSource.Position = index;
		}

		private void btnBrowse_Click(object? sender, EventArgs e)
		{
			var boundItem = GetSelectedTask();
			if (boundItem == null)
			{
				MessageBox.Show("当前没有可编辑的任务行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			using var dialog = new FolderBrowserDialog();
			dialog.Description = "选择要清理的目录";
			dialog.ShowNewFolderButton = false;
			if (!string.IsNullOrWhiteSpace(boundItem.Path))
				dialog.SelectedPath = boundItem.Path;

			var result = dialog.ShowDialog(this);
			if (result == DialogResult.OK && !string.IsNullOrEmpty(dialog.SelectedPath))
			{
				boundItem.Path = dialog.SelectedPath;
				// 刷新绑定源以更新界面显示
				_bindingSource.ResetBindings(false);
				gridTasks.EndEdit();
				_bindingSource.EndEdit();
				SaveConfig();
			}
		}

		private void btnAdd_Click(object? sender, EventArgs e)
		{
			// 暂停重绘以减少闪烁
			gridTasks.SuspendLayout();
			try
			{
				var newTask = new Models.DeleteTask
				{
					Name = "新任务",
					Path = "",
					IncludeSubdirectories = true,
					Basis = Models.TimeBasis.ModifiedTime,
					OlderThanDays = 30,
					SearchPattern = "*",
					Enabled = true
				};
				_config.Tasks.Add(newTask);
				_bindingSource.ResetBindings(false);
				
				// 选中新添加的行
				if (gridTasks.Rows.Count > 0)
				{
					gridTasks.CurrentCell = gridTasks.Rows[gridTasks.Rows.Count - 1].Cells["Name"];
					gridTasks.Rows[gridTasks.Rows.Count - 1].Selected = true;
				}
				SaveConfig();
			}
			finally
			{
				// 恢复重绘
				gridTasks.ResumeLayout();
			}
		}

		private void btnRemove_Click(object? sender, EventArgs e)
		{
			var boundItem = GetSelectedTask();
			if (boundItem == null)
				return;
			var confirm = MessageBox.Show($"确认删除任务: {boundItem.Name}?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
			if (confirm != DialogResult.Yes) return;
			
			// 暂停重绘以减少闪烁
			gridTasks.SuspendLayout();
			try
			{
				_config.Tasks.Remove(boundItem);
				_bindingSource.ResetBindings(false);
				SaveConfig();
			}
			finally
			{
				// 恢复重绘
				gridTasks.ResumeLayout();
			}
		}

		private void GridTasks_DataBindingComplete(object? sender, DataGridViewBindingCompleteEventArgs e)
		{
			UpdateRowNumbers();
		}

		private void UpdateRowNumbers()
		{
			// 暂停重绘以减少闪烁
			gridTasks.SuspendLayout();
			try
			{
				// 若不存在序号列则直接返回，避免运行时错误
				if (gridTasks.Columns["RowNumber"] == null)
				{
					return;
				}
				for (int i = 0; i < gridTasks.Rows.Count; i++)
				{
					gridTasks.Rows[i].Cells["RowNumber"].Value = (i + 1).ToString();
				}
			}
			finally
			{
				// 恢复重绘
				gridTasks.ResumeLayout();
			}
		}
	}
}
